<template>
  <div class="valid-code">
    <canvas ref="canvas" @click="handleClick"></canvas>
  </div>
</template>

<script>
export default {
  name: 'ValidCode',
  data() {
    return {
      code: ''
    }
  },
  mounted() {
    this.draw()
  },
  methods: {
    // 生成随机验证码
    generateCode() {
      const chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'
      let code = ''
      for (let i = 0; i < 4; i++) {
        code += chars.charAt(Math.floor(Math.random() * chars.length))
      }
      return code
    },
    // 绘制验证码
    draw() {
      const canvas = this.$refs.canvas
      canvas.width = 100
      canvas.height = 40
      const ctx = canvas.getContext('2d')
      
      // 生成新的验证码
      this.code = this.generateCode()
      
      // 清空画布
      ctx.clearRect(0, 0, canvas.width, canvas.height)
      
      // 绘制背景
      ctx.fillStyle = '#f5f5f5'
      ctx.fillRect(0, 0, canvas.width, canvas.height)
      
      // 绘制文字
      ctx.font = '24px Arial'
      ctx.fillStyle = '#333'
      for (let i = 0; i < this.code.length; i++) {
        const x = 20 + i * 20
        const y = 25 + Math.random() * 8
        const deg = Math.random() * 30 * Math.PI / 180
        ctx.translate(x, y)
        ctx.rotate(deg)
        ctx.fillText(this.code[i], 0, 0)
        ctx.rotate(-deg)
        ctx.translate(-x, -y)
      }
      
      // 绘制干扰线
      for (let i = 0; i < 4; i++) {
        ctx.strokeStyle = this.randomColor(40, 180)
        ctx.beginPath()
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height)
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height)
        ctx.stroke()
      }
      
      // 绘制干扰点
      for (let i = 0; i < 20; i++) {
        ctx.fillStyle = this.randomColor(0, 255)
        ctx.beginPath()
        ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1, 0, 2 * Math.PI)
        ctx.fill()
      }
      
      // 触发事件，将验证码传递给父组件
      this.$emit('update:value', this.code)
    },
    // 生成随机颜色
    randomColor(min, max) {
      const r = Math.floor(Math.random() * (max - min) + min)
      const g = Math.floor(Math.random() * (max - min) + min)
      const b = Math.floor(Math.random() * (max - min) + min)
      return `rgb(${r},${g},${b})`
    },
    // 点击刷新验证码
    handleClick() {
      this.draw()
    }
  }
}
</script>

<style scoped>
.valid-code {
  display: inline-block;
  cursor: pointer;
}
canvas {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  vertical-align: middle;
}
</style> 